<?php
/**
 * Created by PhpStorm.
 * User: 跳梁
 * Date: 2015/11/3
 * Time: 11:24
 */
class MessageReplyAction extends Action{
    public function getAllReply($messageTags=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $activeReply = M("module_active_reply");
        Session::switchCustomer($customerId);
        $accessTagModel = M("access_tag");
        $condition["customerId"] = $customerId;
        isset($messageTags)&&$messageTags?$condition["messageTags"]=$messageTags:"";
        $list = $activeReply->where($condition)->limit($start,$limit)->select();
        foreach($list as $key=>$value){
            $where["id"] = array("in",$value["messageTags"]);
            $tagNames = $accessTagModel->where($where)->field("GROUP_CONCAT(tagName) as tagName")->find();
            $list[$key]['messageTags'] = $tagNames["tagName"];
        }
        if($list){
            $count = $activeReply->where($condition)->count();
            Output::instance()->objArray($list,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    public function getReplyById($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $activeReply = M("module_active_reply");
        Session::switchCustomer($customerId);
        $accessTags = M("access_tag");
        $condition["a.customerId"] = $customerId;
        $condition["a.id"] = $id;
        $replyInfo = $activeReply->alias("a")
            ->join("left join wx_".$customerId."_material b on a.materialId=b.id")
            ->field("a.*,b.xml as materialComment")
            ->where($condition)->find();
        $replyInfo["accessTags"] = $accessTags->select();
        if($replyInfo["messageTags"]){
            $replyInfo["messageTags"] = explode(",",$replyInfo["messageTags"]);
            foreach($replyInfo["accessTags"] as $i=>$tag){
                $replyInfo["accessTags"][$i]["checked"]=0;
                foreach($replyInfo["messageTags"] as $j=>$message){
                    if($message==$tag["id"]){
                        $replyInfo["accessTags"][$i]["checked"]=1;
                    }
                }
            }
        }
        $rule = json_decode($replyInfo["rule"],true);
        switch($rule["module"]){
            case 'order':
                $replyInfo["orderNum"] = $rule["num"];
                break;
        }
        Output::instance()->object($replyInfo);
    }
    public function saveReply($id,$sortNumber=null,$materialId=null,$messageTags=null,$rule=null,$runTime=null){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $activeReply = M("module_active_reply");
        Session::switchCustomer($customerId);
        $nowTime = date("Y-m-d H:i:s");
        $data["customerId"] = $customerId;
        $data["sortNumber"] = $sortNumber;
        $data["materialId"] = $materialId;
        $data["messageTags"] = $messageTags;
        $data["rule"] = $rule;
        $data["runTime"] = $runTime;
        $data["updateTime"] = $nowTime;
        if($id){
            $condition["id"] = $id;
            $result = $activeReply->where($condition)->save($data);
        }else{
            $data["createTime"] = $nowTime;
            $result = $activeReply->add($data);
        }
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    public function getDetailById($id,$nickname=null,$startTime=null,$endTime=null,$start=0,$limit=10){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $activeReplyDetail = M("module_active_reply_detail");
        Session::switchCustomer($customerId);
        $condition["a.activeReplyId"] = array("eq",$id);
        isset($nickname)&&$nickname?$condition["b.nickname"]=array("like","%".$nickname."%"):"";
        isset($startTime)&&$startTime?$condition["a.createTime"] = array("egt",$startTime):"";
        isset($endTime)&&$endTime?$condition["a.createTime"] = array("elt",$endTime):"";
        $list = $activeReplyDetail->alias("a")
            ->join("left join wx_".$customerId."_user_weixin_info b on a.userName=b.openid")
            ->where($condition)
            ->field("a.*,b.nickname,b.headimgurl")
            ->limit($start,$limit)
            ->order("a.createTime desc")
            ->select();
        if($list){
            $count = $activeReplyDetail->alias("a")
                ->join("left join wx_".$customerId."_user_weixin_info b on a.userName=b.openid")
                ->where($condition)
                ->field("a.*,b.nickname,b.headimgurl")
                ->count();
            Output::instance()->objArray($list,$count);
        }else{
            Output::instance()->resultCode();
        }
    }
    public function delete($id){
        $retVal = Session::init();
        if (!$retVal) {
            Output::instance()->resultCode(code_access_denied);
            return;
        }
        $customerId = Session::$user["customerId"];
        Session::switchCustomer(0);
        $activeReply = M("module_active_reply");
        Session::switchCustomer($customerId);
        $condition["id"] = array("eq",$id);
        $result = $activeReply->where($condition)->delete();
        if($result){
            Output::instance()->resultCode();
        }else{
            Output::instance()->resultCode(code_sql_error);
        }

    }
    public function sendMassageToUser(){
        Session::switchCustomer(0);
        $activeReply = M("module_active_reply");
        $activeDetail = M("module_active_reply_detail");
        $replyList = $activeReply->order("sortNumber")->select();
        foreach($replyList as $key=>$reply){
            $customerId = $reply["customerId"];
            Session::switchCustomer($customerId);
            $userModule = M("user");
            $rule = json_decode($reply["rule"],true);
            $runtime = $reply["runTime"];
            $runTime = time()-$runtime*60*60;
            $nowTime = date("Y-m-d H:i:s",time()-48*60*60);
            $time = date('Y-m-d H:i:s',$runTime);
            switch($rule["module"]){
                case 'order':
                    $userList = $userModule->alias("a")
                        ->join("inner join wx_".$customerId."_user_access_tag b on a.userName = b.fromUserName")
                        ->join("left join wx_module_product_order c on a.userName = c.fromUserName")
                        ->join("left join wx_".$customerId."_user_weixin_info e on a.userName = e.openid")
                        ->where("a.lastTime <'". $time."' and a.lastTime > '".$nowTime."' and a.status <> 'sharesubscribe' and a.status <> 'unsubscribe' and b.accesstagid in (".$reply["messageTags"].")")
                        ->field("a.userName,e.nickname,group_concat(DISTINCT(c.id)) as orders")
                        ->group("a.id")
                        ->select();
                    Log::write($userModule->getLastSql());
                    foreach($userList as $i=>$user){
                        $orderCount=0;
                        if($user["orders"]){
                            $orderCount = count($user["orders"]);
                        }
                        $where["userName"] = array("eq",$user["userName"]);
                        $where["activeReplyId"] = array("eq",$reply["id"]);
                        $replyCount = $activeDetail->where($where)->count();
                        if(!$replyCount&&$orderCount>=$rule["num"]){
                           self::sendMessage($reply["materialId"],$customerId,$user["userName"],$reply["id"],$user["nickname"]);
                        }
                    }
                break;
            }
        }

    }
    public function sendMessage($materialId,$customerId,$userName,$replyId,$nickname){
        Session::switchCustomer(0);
        $replyDetail = M("module_active_reply_detail");
        Session::switchCustomer($customerId);
        $materialModule = M("material");
        $materialInfo = $materialModule->where("id=".$materialId)->find();
        if(!$materialInfo){
            return;
        }
        $xml = (string)$materialInfo["xml"];
        $xml = str_replace("{{nickname}}",$nickname,$xml);
        $xml = simplexml_load_string($xml,'SimpleXMLElement', LIBXML_NOCDATA);
        $item = $xml->Articles->item;
        $articles=array();
        foreach($item as $key=>$value){
            $article=new stdClass();
            $article->title = urlencode((string)$value->title);
            $article->url = urlencode((string)$value->url);
            $article->picurl = urlencode((string)$value->picUrl);
            $article->description = urlencode((string)$value->description);
            array_push($articles, $article);
        }
        $toUser = $userName;
        $result = WeixinApi::sendServiceMsg($toUser, 'news','',$articles);
        Log::write(var_dump($result));
        $str = json_encode($articles,true);
        $data["activeReplyId"] = $replyId;
        $data["userName"]= $userName;
        if($result->errcode){
            $data["result"] = 0;
        }else{
            $data["result"] = 1;
        }
        $data["message"] = $str;
        $data["createTime"] = date("Y-m-d H:i:s");
        $replyDetail->add($data);
    }
}